class Layers {
    constructor() {
        this.elements = [];
        this._sel = null;
    }

    add(elem) {
        this.elements.push(elem);
    }

    remove(elem) {
        let index = this.elements.indexOf(elem);
        if (index !== -1) {
            this.elements.splice(index, 1);
        }
    }

    clear() {
        this.elements = [];
    }

    traverse(callback) {
        for (let i = 0; i < this.elements.length; i++) {
            const e = this.elements[i];
            callback && callback(e, i);
        }
    }

    // 将选中对象上移一层
    moveUp(elem) {
        let index = this.elements.indexOf(elem);
        if (index < 0 || index >= this.elements.length - 1) {
            return;
        }

        let toIndex = index + 1;
        let toElement = this.elements[toIndex];
        this.elements[index] = toElement;
        this.elements[toIndex] = elem;
    }


    // 将选中对象下移一层
    moveDown(elem) {
        let index = this.elements.indexOf(elem);
        if (index <= 0) {
            return;
        }

        let toIndex = index - 1;
        let toElement = this.elements[toIndex];
        this.elements[index] = toElement;
        this.elements[toIndex] = elem;
    }

    // 移到顶部
    moveFront(elem) {
        let index = this.elements.indexOf(elem);
        if (index > -1) {
            let count = this.elements.length - index;
            for (let i = 0; i < count; i++) {
                this.moveUp(elem);
            }
        }
    }

    // 移到底部
    moveBack(elem) {
        let index = this.elements.indexOf(elem);
        if (index > -1) {
            let count = index;
            for (let i = 0; i < count; i++) {
                this.moveDown(elem);
            }
        }
    }

    setHover(elem) {
        if (elem && elem.forceState != 'selected') {
            this.elements.forEach(e => {
                if (e.forceState != 'selected') {
                    e.setForceState('normal');
                }
            });
            elem.setForceState('focus');
        }
    }

    removeHover(elem) {
        if (elem && elem.forceState != 'selected') {
            elem.setForceState('normal');
        }
    }

    selectElement(elem) {
        if (elem) {
            this._sel = elem;
            this.elements.forEach(e => {
                e.setForceState('normal');
            });
            elem.setForceState('selected');
        }
    }

    getSelectedElement() {
        return this._sel;
    }

    unSelectAll() {
        if (this._sel) {
            this._sel.setForceState('normal');
        }
        this._sel = null;
    }

    // 找出边界包含鼠标当前位置的元素集合
    findHoverElements(context, x, y) {
        let els = [];
        this.elements.forEach(e => {
            if (e.containsPoint(context, x, y)) {
                els.push(e);
            }
        });
        return els;
    }
}


export { Layers };